import React, {useEffect, useState} from 'react';
import {Col, Layout, message as antMessage, Row} from 'antd';
import ChangeTable from "../changeTable";
import useWebSocket, {Message} from "../../hook/UseWebSocket";
import CanvasComponent from "../canvasVideo";
import {TableIDataType} from "../changeTable/data";
import moment from "moment";
import {IPoint} from "../../metadata/PointData";
import {calculateDistance} from "../../utils/commandJS";


const {Header, Content} = Layout;
const HomePage: React.FC = () => {
    const [message, setMessage] = useState<Message>()
    const [cameraData, setCameraData] = useState<ICameraData>()
    const [protonData, setProtonData] = useState<IProtonData>()
    const [tableData, setTableData] = useState<TableIDataType[]>([])
    const [peopleHistory, setPeopleHistory] = useState<IPeopleData[]>([])
    //const [minHeadNum, setMinHeadNum] = useState<number>(0)
    const [isModalOpen, setIsModalOpen] = useState(false);
    // const [lastPeoplePoint, setLastPeoplePoint] = useState<IPointNumber>({point: {x: 0, y: 0}, number: 0})
    const [jsonVersion, setJsonVersion] = useState(0)
    const [timer, setTimer] = useState<any>(null)
    useWebSocket({
        url: `ws://127.0.0.1:8889`,
        onOpen: () => {
        },
        onClose: () => {
        },
        onError: () => {
        },
        onMessage: (message) => {
            setMessage(message)
        },
    });
    const getConfigData = async () => {
        const response = await fetch('../../../config.json');
        const config: any = await response.json();
        localStorage.setItem('config', JSON.stringify(config));
    }

    const watchConfig = async () => {
        setTimer(setInterval(async () => {
            const response = await fetch('../../../config.json');
            const config: any = await response.json();
            setJsonVersion(jsonVersion + 1)
            localStorage.setItem('config', JSON.stringify(config));
        }, 800))
    }
    /**
     * 监听是否在踩点
     */
    useEffect(() => {
        if (isModalOpen) {
            watchConfig()
        } else {
            setTimer(null)
            clearInterval(timer)
        }

    }, [isModalOpen]);


    /**
     * 初始化获取config数据
     */
    useEffect(() => {
        getConfigData().then();
    }, []);

    /**
     * 监听数据变化
     */
    useEffect(() => {
        if (!message) return
        // 摄像头数据
        if (message?.data.imageDataByte) {
            setPeopleHistory([])
            setCameraData(message.data as ICameraData)
            const peopleData: IPeopleData = {
                checkedPeopleData: message.data.checkedPeople,
                checkedPeopleNum: message.data.checkedPeopleNum,
                time: moment().format('YYYY/MM/DD HH:mm:ss SSS')
            }
            //处理人员识别数据
            if (peopleHistory.length > 0) {
                setPeopleHistory([peopleData, ...peopleHistory])
            } else {
                setPeopleHistory([peopleData])
            }
        }
        console.log("message?.data.header.action", message?.data?.payload?.itemList)
        // proton数据
        if (message?.data.payload?.itemList && message?.data?.header?.action == 'dau_weight_count.upload') {
            setProtonData(message.data as IProtonData)
        }
    }, [message]);

    /**
     * 清理缓存数据
     */
    useEffect(() => {
        if (peopleHistory.length > 1000) {
            const updatedPeopleHistory = peopleHistory.slice(0, 5);
            setPeopleHistory(updatedPeopleHistory);
        }
    }, [peopleHistory]);

    /**
     * 监听protonData数据变化
     */
    useEffect(() => {
        if (protonData?.payload?.itemList) {
            protonData.payload.itemList.forEach((item) => {
                    let miniHeadNum = null; // 存储最小距离对应的头编号
                    let minDistance = Infinity;
                    let lastPeoplePoint: { point: any; number: any; };
                    const tableProtonWeightCount = item.weightCount;
                    const regex: RegExp = /L(\d+-\d+-\d+)$/;
                    const match: RegExpMatchArray | null = item.dau.match(regex);
                    if (match) {
                        //根据正则表达式获取仓库号
                        const result: string = "L" + match[1];
                        const configString = localStorage.getItem("config")
                        const config = configString ? JSON.parse(configString) : 'null';
                        if (config == 'null') {
                            antMessage.error('未检测到库位json配置，请点击logo进行配置').then();
                            return;
                        }
                        if (config[result]) {
                            const {x, y} = config[result];
                            const DauPoint: IPoint = {x, y};
                            //根据peopleHistory里的第一个checkedPeopleData的headX和headY
                            const lastPeopleData = peopleHistory[0]
                            if (lastPeopleData.checkedPeopleData?.length == 0) return;
                            //只有一个人
                            if (lastPeopleData.checkedPeopleData?.length == 1) {
                                miniHeadNum = lastPeopleData.checkedPeopleData[0].headNum
                            } else if (lastPeopleData?.checkedPeopleData!.length > 1) {
                                //多个人
                                //欧几里得距离
                                lastPeopleData.checkedPeopleData?.forEach((currentPeople) => {
                                    // 计算当前人到DauPoint的距离
                                    const currentDistance = calculateDistance({
                                        x: currentPeople.headX,
                                        y: currentPeople.headY
                                    }, DauPoint);

                                    // 如果当前人比当前最小距离更近，更新最小距离和对应的编号
                                    if (currentDistance < minDistance) {
                                        minDistance = currentDistance;
                                        miniHeadNum = currentPeople.headNum;
                                        lastPeoplePoint = {
                                            point: {x: currentPeople.headX, y: currentPeople.headY},
                                            number: currentPeople.headNum
                                        };
                                    }
                                    // 如果当前人的距离和最小距离相同，则选择距离更左边的作为最小距离对应的人
                                    else if (currentDistance === minDistance) {
                                        // 比较 x 坐标，选择最左边的
                                        if (currentPeople.headX < lastPeoplePoint.point.x) {
                                            miniHeadNum = currentPeople.headNum;
                                            lastPeoplePoint = {
                                                point: {x: currentPeople.headX, y: currentPeople.headY},
                                                number: currentPeople.headNum
                                            };
                                        }
                                    }
                                });
                                console.log("========开始渲染")
                            }
                            const startTime = new Date().getTime();
                            while (new Date().getTime() - startTime < 1) {
                                console.log("等待1ms")}
                            //渲染表格数据
                            const taleData = {
                                createTime: moment().format('YYYY/MM/DD HH:mm:ss SSS'),
                                customerNo: miniHeadNum ? miniHeadNum : '',
                                WarehouseNo: result || '',
                                VariableQuantity: tableProtonWeightCount,
                            } as TableIDataType;
                            tableData.unshift(taleData)
                            setTableData(JSON.parse(JSON.stringify(tableData)))
                        }
                    }
                }
            )
        }
    }, [protonData])


    return (
        <Layout style={{background: '#181c2c'}}>
            <Header
                style={{
                    display: 'flex',
                    justifyContent: 'flex-start',
                    border: '2px solid white',
                    color: 'white',
                    cursor: "pointer"
                }}>
                {isModalOpen ?
                    <button onClick={() => {
                        setIsModalOpen(false);
                        console.log('点击了', isModalOpen)
                    }}>结束踩点</button> :
                    <div style={{display: 'flex', justifyContent: 'center'}}>
                        <img src="../../../img.png" style={{height: 50, width: 50, marginRight: 20}}
                             alt={'logo'} onClick={() => setIsModalOpen(true)}/>
                        <span>人货识别系统</span>
                    </div>
                }
            </Header>
            <Content>
                <Row style={{border: '1px solid white'}}>
                    <Col span={16}>
                        <div style={{
                            display: "flex",
                            justifyContent: "center",
                            alignItems: "center",
                            height: "100%",
                        }}>
                            {cameraData?.imageDataByte && cameraData.imageDataByte.length > 0 && (
                                <CanvasComponent byteData={cameraData.imageDataByte as number[]}
                                                 jsonVersion={jsonVersion}
                                                 showJsonPoint={isModalOpen}
                                                 checkedPeople={cameraData.checkedPeople}
                                                 currentDetectionAreaRightTopY={cameraData.currentDetectionAreaRightTopY}
                                                 currentDetectionAreaLeftBottomX={cameraData.currentDetectionAreaLeftBottomX}
                                                 currentDetectionAreaLeftBottomY={cameraData.currentDetectionAreaLeftBottomY}
                                                 currentDetectionAreaLeftTopX={cameraData.currentDetectionAreaLeftTopX}
                                                 currentDetectionAreaLeftTopY={cameraData.currentDetectionAreaLeftTopY}
                                                 currentDetectionAreaRightBottomX={cameraData.currentDetectionAreaRightBottomX}
                                                 currentDetectionAreaRightBottomY={cameraData.currentDetectionAreaRightBottomY}
                                                 currentDetectionAreaRightTopX={cameraData.currentDetectionAreaRightTopX}/>
                            )}
                        </div>

                    </Col>
                    <Col span={8}>
                        <div
                            style={{borderLeft: '2px solid white', height: 700}}>
                            <ChangeTable data={tableData}/>
                        </div>
                    </Col>
                </Row>
                <div style={{color: 'white'}}>
                    <Row style={{border: '2px solid white'}}>
                        <Col span={12}>
                            <div
                                style={{border: '1px solid white', height: '100vh'}}>
                                {protonData?.payload?.itemList.map((item, index) => {
                                    return <div
                                        style={{height: 500, overflow: 'auto', padding: 10}}
                                        key={index}>
                                        库位号： <span>{item.dau}</span>
                                        <br/>
                                        重力变化：<span>{item.weight}</span>
                                        <br/>
                                        剩余数量：<span>{item.weightCount}</span>
                                    </div>
                                })}
                            </div>
                        </Col>
                        <Col span={12}>
                            <div style={{border: '1px solid white', height: 300, overflow: 'auto', padding: 10}}>
                                {
                                    cameraData?.checkedPeople.map((item, index) => {
                                        return (
                                            <div key={index}>
                                                第{index + 1} 个人人头编号： <span>{item.headNum}</span>
                                                <br/>
                                                第{index + 1} 个人人头X坐标： <span>{item.headX}</span>
                                                <br/>
                                                第{index + 1} 个人人头Y坐标： <span>{item.headY}</span>
                                                <br/>
                                                第{index + 1} 个人的身高 <span>{item.height}</span>
                                                <br/>
                                                第{index + 1} 个人的追踪状态 <span>{item.trackStatus}</span>
                                                <hr/>
                                            </div>
                                        );
                                    })}
                            </div>
                        </Col>
                    </Row>
                </div>
            </Content>
        </Layout>
    );
};

export default HomePage;